/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.bootstrap.client.ui;

import java.util.List;

import com.cleangwt.user.client.HashTokenizer;
import com.cleangwt.user.shared.Link;
import com.cleangwt.user.shared.Links;

/**
 * A {@link Navigator} for page linking and accepts {@link Link}s to render navigator items. If the
 * link is a node with sub links, an dropdown item will created.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 */
public class PageNavigator extends Navigator {
  private List<Link> links;

  /**
   * Creates a page navigator.
   */
  public PageNavigator() {
    super();
  }

  /**
   * Creates a page navigator with the given base style.
   * 
   * @param style the base style
   */
  public PageNavigator(String style) {
    super(style);
  }

  /**
   * Sets the links.
   * 
   * @param links the links to render a page link or or a dropdown with sub links .
   */
  public void setLinks(List<Link> links) {
    this.links = links;
    getElement().setInnerText("");
    for (Link link : links) {
      if (link.getValue() != null) {
        this.addLink(link.getName(), HashTokenizer.packPageHash(link.getValue()));
      } else if (link.getSubLinks() != null) {
        DropdownBuilder dropdown = this.addDropdown(link.getName());
        for (Link sub : link.getSubLinks()) {
          dropdown.addLink(sub.getName(), HashTokenizer.packPageHash(sub.getValue()));
        }
      } else {
        throw new IllegalArgumentException();
      }

    }
  }

  /**
   * Sets the active page.
   * 
   * @param pageName the page name
   */
  public void setActivePage(String pageName) {
    if (pageName == null) {
      setActive(-1);
    } else {
      this.setActive(links.indexOf(Links.getRoot(links, pageName)));
    }
  }
}
